/**
 * @decription 路由入口
 * @author 印明帝
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import login from './login'
import register from './register'
import notFound from './404'
import error from './error'
import setting from './setting'
import home from './home'
import profile from './profile'
import square from './square'
import atMe from './atMe'
import { inCookie } from 'utils/cookie'

Vue.use(VueRouter)

// routes
const routes = [
  login,
  register,
  notFound,
  setting,
  home,
  profile,
  square,
  error,
  atMe
]

const router = new VueRouter({
  routes,
  mode: 'history'
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 判断是否访问login和register页面
  let isLogin = inCookie('weibo.sid')
  if (to.meta.requireAuth) {
    if (isLogin) {
      next()
    } else {
      next({ path: '/login' })
    }
  } else {
    next()
  }

  /* 如果本地 存在 cookie 则 不允许直接跳转到 登录页面 */
  if (to.fullPath === '/login' || to.fullPath === '/register') {
    if (isLogin) {
      next({
        path: from.fullPath
      })
    } else {
      next()
    }
  }
})

export default router
